<?php


namespace App\Service\Cooperative;


use App\Constants\ContextKey;
use App\Constants\Model\UserWithdraw;
use App\Dao\UserDao;
use App\Dao\UserWithdrawDao;
use App\Model\UserWithdrawLog;
use App\Utils\Log;
use App\Utils\Notice\Sender;
use App\Utils\Notice\UserWithdrawReject;
use App\Utils\Notice\UserWithdrawSuccess;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;

class WithdrawalCashService extends BaseService
{

    /**
     * @Inject()
     * @var UserWithdrawDao
     */
    protected $userWithdrawDao;

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;


    /**
     * @param array $where
     * @return array
     */
    public function index(array $where): array
    {
        $where['is_self_merchant'] = UserWithdraw::IS_SELF_MERCHANT_YES;
        $pageInfo = $this->extractPaginateInfo($where);
        $where['cooperative_id'] = $this->user()->cooperative_id;
        $where['status'] = isset($where['status']) ? $where['status'] : 0;
        $index = $this->userWithdrawDao->where($where)->with('user')->paginate(
            $pageInfo['perPage'],['*'],'page',$pageInfo['page']
        );
        return $this->formatIndex($index);
    }

    public function formatIndex(\Hyperf\Contract\LengthAwarePaginatorInterface $index)
    {
        $data = [];
        /** @var \App\Model\UserWithdraw $userWithdraw */
        foreach ($index->items() as $userWithdraw) {
            $data[] = [
                'id' => $userWithdraw->id,
                'user_name' => $userWithdraw->user->nickname,
                'user_avatar' => $userWithdraw->user->avatar,
                'phone' => $userWithdraw->user->phone,
                'ali_account' => $userWithdraw->user->alipay,
                'amount' => $userWithdraw->amount,
                'message' => $userWithdraw->message,
                'created_at' => $userWithdraw->created_at->toDatetimeString(),
                'status' => $userWithdraw->status
            ];
        }
        return [
            'data' => $data,
            'current_page' => $index->currentPage(),
            'total' => $index->total(),
            'per_page' => $index->perPage()
        ];
    }


    /**
     * 确认
     * @param $data
     * @return bool
     */
    public function ackApply($data)
    {
        /** @var \App\Model\UserWithdraw $userWithDraw */
        $userWithDraw = $this->userWithdrawDao->firstOrThrow(
            [
                'id' => $data['id'],
                'status' => UserWithdraw::STATUS_PENDING,
                'cooperative_id' => $this->user()->cooperative_id
            ]
        );
        $userWithDraw->status = UserWithdraw::STATUS_ON;
        return $userWithDraw->save();
    }


    /**
     * 驳回
     * @param $data
     * @return bool
     */
    public function rejectApply($data)
    {
        /** @var \App\Model\UserWithdraw $userWithDraw */
        $userWithDraw = $this->userWithdrawDao->firstOrThrow(
            [
                'id' => $data['id'],
                'status' => UserWithdraw::STATUS_PENDING,
                'cooperative_id' => $this->user()->cooperative_id
            ]
        );
        $userWithDraw->status = UserWithdraw::STATUS_FAIL;
        $userWithDraw->message = $data['message'];

        //通知用户提现被驳回
        Sender::send($userWithDraw->user_id, new UserWithdrawReject());

        return $userWithDraw->save();
    }


    /**
     * 已打款
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function paidApply($data)
    {
        /** @var \App\Model\UserWithdraw $userWithDraw */
        $userWithDraw = $this->userWithdrawDao->firstOrThrow(
            [
                'id' => $data['id'],
                'status' => UserWithdraw::STATUS_ON,
                'cooperative_id' => $this->user()->cooperative_id
            ]
        );

        Db::beginTransaction();
        try {
            $userWithDraw->status = UserWithdraw::STATUS_SUCCESS;
            $userWithDraw->save();
            //写日志
            $userWithDrawLog = new UserWithdrawLog(
                [
                    'user_id' => $userWithDraw->user_id,
                    'cooperative_id' => $userWithDraw->cooperative_id,
                    'user_with_draw_id' => $userWithDraw->id,
                    'gold' => $userWithDraw->gold,
                    'gold_type' => $userWithDraw->gold_type,
                    'is_self_merchant' => $userWithDraw->is_self_merchant,
                    'receive_account' => $userWithDraw->user->alipay
                ]
            );
            $userWithDrawLog->save();

            //发送提现成功通知
            Sender::send($userWithDraw->user_id, new UserWithdrawSuccess([
                'replaces' => [
                    'amount' => bcdiv((string)$userWithDraw->gold, '100', 2)
                ]
            ]));

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            Log::get()->error(
                $exception->getMessage(),
                [
                    'class:method' => __CLASS__ . ':' . __METHOD__,
                    'userWithDrawId' => $data['id']
                ]
            );
            throw $exception;
        }
        return true;
    }

}